package cn.edu.ncut.cs.springboot.petmanagementsystem.controller;

import cn.edu.ncut.cs.springboot.petmanagementsystem.common.Result;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.StatisticsService;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/statistics")
@Tag(name = "数据统计模块")
public class StatisticsController {

    @Autowired
    private StatisticsService statisticsService;

    @Autowired
    private UserService userService;

    @Operation(summary = "获取用户数据统计")
    @GetMapping("/user")
    public Result<?> getUserStatistics() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            Map<String, Object> statistics = statisticsService.getUserStatistics(user.getId());
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取用户统计失败", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取宠物健康趋势")
    @GetMapping("/health-trend/{petId}")
    public Result<?> getHealthTrend(
            @Parameter(description = "宠物ID") @PathVariable Long petId,
            @Parameter(description = "月数") @RequestParam(defaultValue = "6") Integer months) {
        try {
            Map<String, Object> trend = statisticsService.getHealthTrend(petId, months);
            return Result.success(trend);
        } catch (Exception e) {
            log.error("获取健康趋势失败", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }
}
